<!-- src/views/user/index.vue -->
<script setup>
import { onMounted, ref, nextTick } from 'vue'
import { AddUserApi, QueryPageApi, QueryUserApi, UpdateUserApi, DeleteUserApi } from '@/api/user';
import { ElMessage, ElMessageBox } from 'element-plus'
import UserForm from '@/views/component/UserForm.vue'

// 弹窗控制
const dialogVisible = ref(false)
// 搜索表单数据
const employForm = ref({
  id: '',
  name: '',
  role: ''
})
// 分页相关
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)
const tableData = ref([])

// 表单数据（新增/修改共用）
const userForm = ref({
  id: '',
  name: '',
  role: '',
  gender: '',
  contactInfo: '',
  whether: 1 // 默认有效
})

// 区分新增还是修改状态
const isEdit = ref(false)

const userFormRef = ref(null)
const tips = ref('新增员工')

// 加载列表数据
const search = async () => {
  try {
    const result = await QueryPageApi(
      employForm.value.id,
      employForm.value.name,
      employForm.value.role,
      currentPage.value,
      pageSize.value
    )
    tableData.value = result.data.rows
    total.value = result.data.total
  } catch (error) {
    ElMessage.error('加载数据失败')
  }
}

// 分页尺寸变化
const handleSizeChange = async (val) => {
  pageSize.value = val
  await search()
}

// 分页页码变化
const handleCurrentChange = async (val) => {
  currentPage.value = val
  await search()
}

// 打开新增弹窗
const handleAdd = () => {
  isEdit.value = false
  tips.value = '新增员工'
  // 重置表单数据
  userForm.value = {
    id: '',
    name: '',
    role: '',
    gender: '',
    contactInfo: '',
    whether: 1
  }
  
  dialogVisible.value = true
  
  // 等待DOM更新后重置表单
  nextTick(() => {
    if (userFormRef.value) {
      userFormRef.value.resetForm()
    }
  })
}

// 打开修改弹窗
const handleEdit = async (row) => {
  if (!row || !row.id) {
    ElMessage.error("无效的用户数据")
    return
  }
  
  isEdit.value = true
  tips.value = '修改员工'
  
  try {
    // 查询用户详细信息
    const result = await QueryUserApi(row.id)
    if (result.code) {
      userForm.value = result.data
      dialogVisible.value = true
    } else {
      ElMessage.error(result.msg || "查询用户信息失败")
    }
  } catch (error) {
    ElMessage.error("查询用户信息失败: " + (error.message || '未知错误'))
  }
}

// 提交表单
const submitForm = async (formData) => {
  try {
    let result;
    if (isEdit.value) {
      // 修改操作
      result = await UpdateUserApi(formData);
    } else {
      // 新增操作
      result = await AddUserApi(formData);
    }

    if (result.code) {
      ElMessage.success(isEdit.value ? "修改成功" : "添加成功");
      dialogVisible.value = false;
      await search(); // 刷新列表
    } else {
      ElMessage.error(result.msg || (isEdit.value ? "修改失败" : "添加失败"));
    }
  } catch (error) {
    ElMessage.error(`网络错误，${isEdit.value ? "修改" : "添加"}失败`);
  }
};

// 关闭弹窗时重置表单
const handleClose = () => {
  dialogVisible.value = false
}

// 删除操作
const handleDelete = async (row) => {
  if (!row) {
    ElMessage.error("数据不存在");
    return;
  }

  if (!row.id) {
    ElMessage.error("用户ID不存在");
    return;
  }

  try {
    await ElMessageBox.confirm(
      `确定要删除员工【${row.name}】吗？`,
      '删除确认',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    const result = await DeleteUserApi(row.id)
    if (result.code) {
      ElMessage.success("删除成功");
      await search();
    } else {
      ElMessage.error(result.msg || "删除失败");
    }
  } catch (error) {
    if (error !== 'cancel' && error.toString().indexOf('cancel') === -1) {
      ElMessage.error("删除失败: " + (error.message || '未知错误'));
    }
  }
}

// 表格选择列回调
const selectable = (row) => {
  return row.whether === 1;
}

// 初始化加载数据
onMounted(() => {
  search()
})
</script>

<template>
  <div class="container">
   <!-- 搜索区域 -->
  <el-form :inline="true" :model="employForm" class="demo-form-inline" style="margin-bottom: 16px;">
    <el-form-item>
      <el-input v-model="employForm.id" placeholder="员工编号" clearable />
    </el-form-item>
    <el-form-item>
      <el-input v-model="employForm.name" placeholder="员工名称" clearable />
    </el-form-item>
    <el-form-item>
      <el-input v-model="employForm.role" placeholder="角色" clearable />
    </el-form-item>
    <el-button type="success" @click="search">搜索</el-button>
    <el-button type="primary" @click="handleAdd">新增</el-button>
  </el-form>
<div calss="table-data">
  <!-- 表格内容 -->
  <el-table :data="tableData" style="width: 100%" border>
    <el-table-column label="#" type="index" width="50" />
    <el-table-column type="selection" :selectable="selectable" width="55" />
    <el-table-column prop="id" label="员工编号" width="180" />
    <el-table-column prop="name" label="员工名称" width="180" />
    <el-table-column prop="role" label="角色" />
    <el-table-column prop="gender" label="性别">
      <template v-slot="scope">
        <el-tag v-if="scope.row.gender === 1">男</el-tag>
        <el-tag v-else>女</el-tag>
      </template>
    </el-table-column>
    <el-table-column prop="contactInfo" label="联系方式" />
    <el-table-column prop="whether" label="是否有效">
      <template v-slot="scope">
        <el-tag v-if="scope.row.whether === 1" type="success">是</el-tag>
        <el-tag v-else type="danger">否</el-tag>
      </template>
    </el-table-column>
    <el-table-column label="操作">
      <template #default="scope">
        <el-button size="small" @click="handleEdit(scope.row)">修改</el-button>
        <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
      </template>
    </el-table-column>
  </el-table>
</div>
  <!-- 弹窗表单 -->
  <el-dialog
    v-model="dialogVisible"
    :title="tips"
    width="500px"
    :before-close="handleClose"
  >
    <UserForm
      ref="userFormRef"
      v-model="userForm"
      :is-edit="isEdit"
      @submit="submitForm"
      @cancel="handleClose"
    />
  </el-dialog>

  <!-- 分页 -->
  <el-pagination
    v-model:current-page="currentPage"
    v-model:page-size="pageSize"
    :page-sizes="[10, 20, 30, 40]"
    :background="true"
    layout="total, sizes, prev, pager, next, jumper"
    :total="total"
    @size-change="handleSizeChange"
    @current-change="handleCurrentChange"
    style="margin-top: 16px; text-align: right"
  />
  </div>
</template>

<style scoped>
.container {
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
  min-height: 100vh;
  padding: 20px;
}

:deep(.el-table) {
  border: 1px solid rgba(255, 255, 255, 0.3);
  margin-bottom: 16px;
  background-color: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(5px);
  border-radius: 8px;
  overflow: hidden;
}

:deep(.el-table th),
:deep(.el-table td) {
  border-right: 1px solid rgba(255, 255, 255, 0.2);
  background-color: rgba(255, 255, 255, 0.1);
  color: #333; /* 确保文字可见 */
}

:deep(.el-table__header-wrapper) {
  background-color: rgba(255, 255, 255, 0.2);
}

/* 确保文字在透明背景上清晰可见 */
:deep(.el-table th),
:deep(.el-table td) {
  color: #333;
}
.table-data{}
</style>